package top.jafar.data.structures;

import java.math.BigDecimal;
import java.security.SecureRandom;
import java.util.concurrent.atomic.AtomicInteger;

public class GamblingGame {
    public static void main(String[] args) {
        for (int i = 0; i < 1000; i++) {
            Gambler gambler = new Gambler(i + 1);
            gambler.startGame();
        }
    }
}

class Gambler implements Runnable {
    private BigDecimal balance = BigDecimal.valueOf(1000);
    private SecureRandom random = new SecureRandom();
    private String name;
    private AtomicInteger playCount = new AtomicInteger(0);

    public Gambler(int index) {
        this.name = "第"+index+"号赌徒";
    }

    public void startGame() {
        new Thread(this).start();
    }

    @Override
    public void run() {
        while (true) {
            if (balance.intValue() < 0) {
                System.out.println(name+"由于余额不足出局，玩了"+playCount.get()+"次");
                break;
            }
            if (playCount.get() > 1000) {
                System.out.println("==="+name+"胜出，余额"+balance.intValue());
                break;
            }
            boolean b = throwCoin();
            if (b) {
                balance = balance.add(BigDecimal.valueOf(200));
//                System.out.println(name+" 第"+playCount.get()+"次结果为+200,余额为"+balance.intValue());
            }else {
                balance = balance.subtract(BigDecimal.valueOf(100));
//                System.out.println(name+" 第"+playCount.get()+"次结果为-100,余额为"+balance.intValue());
            }
            playCount.addAndGet(1);
        }
    }

    private boolean throwCoin() {
        int nextInt = random.nextInt(2);
        return nextInt == 1;
    }
}
